﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using coffeeshop.coffeeDataSetTableAdapters;
using System.Data;
namespace coffeeshop.Models
{
    public class WorkTime
    {
        private static WorkTimeTableAdapter _adapter = new WorkTimeTableAdapter();

        public int UserId { get; set; }
        public coffeeshop.Global.CaLamViec PeriodType { get; set; }
        public DateTime ForDate { get; set; }
        public int WorkTimeId { get; set; }
        public bool IsFinished { get; set; }

        public bool Save()
        {
            try
            {
                if (WorkTimeId > 0)
                {
                    throw new NotImplementedException("Chưa cho phép cập nhật ca làm việc");
                }

                coffeeDataSet.WorkTimeDataTable data = _adapter.AddWorkTime(UserId, (byte)PeriodType, ForDate.ToShortDateString());
                WorkTimeId = (int)data.Rows[0]["WorkTimeId"];
                return true;
            }

            catch
            {
                return false;
            }
        }

        public bool SetFinish()
        {
            try
            {
                if (WorkTimeId == 0)
                {
                    throw new InvalidOperationException("Chưa tạo ca, không cho set finish");
                }
                int result = _adapter.SetFinish(WorkTimeId);

                return result == 1;
            }
            catch
            {
                return false;
            }
        }

        public static WorkTime GetCaLamViecCuoi()
        {
            coffeeDataSet.WorkTimeDataTable data = _adapter.GetLastWorkTime(DateTime.Now.ToShortDateString());
            WorkTime _workTime = new WorkTime();
            if (data.Any())
            {
                _workTime.WorkTimeId = (int)data.Rows[0]["WorkTimeId"];
                _workTime.UserId = (int)data.Rows[0]["UserId"];
                _workTime.PeriodType = (Global.CaLamViec)Enum.Parse(typeof(Global.CaLamViec), data.Rows[0]["PeriodType"].ToString());
                _workTime.IsFinished = bool.Parse(data.Rows[0]["IsFinished"].ToString());
                _workTime.ForDate = (DateTime)data.Rows[0]["ForDate"];
            }

            return _workTime;
        }

        public DataTable getSaleProductInWorkingTime(int _workingtime)
        {
            DataTable dt = new DataTable();
            if (_adapter.GetSaleProductInWorkingTime(_workingtime).Any())
            {
                dt = _adapter.GetSaleProductInWorkingTime(_workingtime);
            }
            return dt;
        }
    }

}
